<template>
  <view class="auth-container">
    <view class="logo-section">
      <image class="logo-image" src="/static/logo.png" mode="aspectFit" />
    </view>

    <!-- <view class="switch-section">
      <text class="switch-text" v-if="!isRegisterMode">没有账号，</text>
      <text class="switch-text" v-else>已有账号，</text>
      <text class="switch-link" @tap="toggleMode">
        {{ isRegisterMode ? '去登录' : '去注册' }}
      </text>
    </view> -->

    <view class="form-section">
      <view class="input-item">
        <input
          class="input-field"
          type="text"
          v-model="formData.username"
          placeholder="请输入用户名"
        />
        <view class="clear-btn" v-if="formData.username" @tap="clearUsername">×</view>
      </view>

      <view class="input-item">
        <input
          class="input-field"
          type="password"
          v-model="formData.password"
          placeholder="密码"
        />
      </view>

      <view class="input-item" v-if="isRegisterMode">
        <input
          class="input-field"
          type="password"
          v-model="formData.confirmPassword"
          placeholder="确认密码"
        />
      </view>

      <view class="input-item" v-if="isRegisterMode">
        <input
          class="input-field"
          type="text"
          v-model="formData.inviteCode"
          placeholder="邀请码"
        />
      </view>

      <!-- <view class="input-item dynamic-code" v-if="!isRegisterMode">
        <input
          class="input-field"
          type="text"
          v-model="formData.dynamicCode"
          placeholder="动态密码"
        />
        <text class="send-code-btn" @tap="sendDynamicCode">发送动态码</text>
      </view> -->
    </view>

    <view class="submit-btn" @tap="handleSubmit">
      {{ isRegisterMode ? '注 册' : '登 录' }}
    </view>

    <view class="privacy-section">
      <view class="privacy-item" @tap="togglePrivacy">
        <view class="checkbox" :class="{ checked: agreedPrivacy }"></view>
        <text class="privacy-text">点击确定您已同意《</text>
        <text class="privacy-link" @tap.stop="viewPrivacy">隐私协议</text>
        <text class="privacy-text">》</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const { appContext } = getCurrentInstance() || {}
const globalProps = appContext?.app?.config?.globalProperties || {}
const api = globalProps.$api
const userUtils = globalProps.$user
const http = globalProps.$http

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  inviteCode: '',
  dynamicCode: ''
})

const agreedPrivacy = ref(false)
const isRegisterMode = ref(false)

const fetchUserDetail = async () => {
  try {
    const detailResponse = await api?.user.getUserInfo()
    if (detailResponse?.entity) {
      userUtils?.saveUserInfo(detailResponse.entity)
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
  }
}

onLoad(() => {
  if (userUtils?.isLoggedIn()) {
    uni.switchTab({
      url: '/pages/studentsPage/student-index'
    })
  }
})

const toggleMode = () => {
  isRegisterMode.value = !isRegisterMode.value
  formData.username = ''
  formData.password = ''
  formData.confirmPassword = ''
  formData.inviteCode = ''
  formData.dynamicCode = ''
}

const clearUsername = () => {
  formData.username = ''
}

const sendDynamicCode = async () => {
  if (!formData.username) {
    uni.showToast({
      title: '请先输入用户名',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '发送中...'
    })

    await api?.user.sendCode(formData.username, 4)

    uni.hideLoading()
    uni.showToast({
      title: '动态码已发送',
      icon: 'success'
    })
  } catch (error) {
    uni.hideLoading()
    console.error('发送动态码失败:', error)
  }
}

const handleSubmit = () => {
  if (!agreedPrivacy.value) {
    uni.showToast({
      title: '请先同意隐私协议',
      icon: 'none'
    })
    return
  }

  if (isRegisterMode.value) {
    handleRegister()
  } else {
    handleLogin()
  }
}

const handleLogin = async () => {
  if (!formData.username || !formData.password) {
    uni.showToast({
      title: '请输入用户名和密码',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '登录中...'
    })

    const response = await api?.user.login(formData.username, formData.password, 4)

    uni.hideLoading()
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })

    if (response?.entity) {
      const userInfo = response.entity
      userUtils?.saveUserInfo(userInfo)
      if (userInfo.tokenId) {
        http?.setToken(userInfo.tokenId)
      }
    }

    await fetchUserDetail()

    setTimeout(() => {
      uni.switchTab({
        url: '/pages/studentsPage/student-index'
      })
    }, 500)
  } catch (error) {
    uni.hideLoading()
    console.error('登录失败:', error)
  }
}

const handleRegister = async () => {
  if (!formData.username || !formData.password || !formData.confirmPassword) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  if (formData.password !== formData.confirmPassword) {
    uni.showToast({
      title: '两次密码输入不一致',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '注册中...'
    })

    await api?.user.register({
      username: formData.username,
      password: formData.password,
      inviteCode: formData.inviteCode
    })

    uni.hideLoading()
    uni.showToast({
      title: '注册成功',
      icon: 'success'
    })

    setTimeout(() => {
      isRegisterMode.value = false
      formData.confirmPassword = ''
      formData.inviteCode = ''
    }, 500)
  } catch (error) {
    uni.hideLoading()
    console.error('注册失败:', error)
  }
}

const togglePrivacy = () => {
  agreedPrivacy.value = !agreedPrivacy.value
}

const viewPrivacy = () => {
  uni.showToast({
    title: '查看隐私协议',
    icon: 'none'
  })
}
</script>

<style lang="scss" scoped>
button {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
  appearance: none !important;
  -webkit-appearance: none !important;
  -moz-appearance: none !important;
}

button::after {
  border: none !important;
  background: none !important;
  content: none !important;
}

.page {
  background:
    linear-gradient(180deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.8) 20%, rgba(255, 255, 255, 1) 100%),
    linear-gradient(270deg, #acfB97 0%, rgba(52, 207, 185, 0) 100%),
    linear-gradient(270deg, rgba(95, 141, 227, 0) 0%, #00c9ff 100%),
    linear-gradient(114deg, #f0fffd 0%, #fcfcfd 100%);
  background-attachment: fixed;
  min-height: 100vh;
}

.auth-container {
  min-height: 100vh;
  padding: 0 44rpx;
  position: relative;
  box-sizing: border-box;
  background:
    linear-gradient(180deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.8) 20%, rgba(255, 255, 255, 1) 100%),
    linear-gradient(270deg, #ACFB97 0%, rgba(52, 207, 185, 0) 100%),
    linear-gradient(270deg, rgba(95, 141, 227, 0) 0%, #00C9FF 100%),
    linear-gradient(114deg, #F0FFFD 0%, #FCFCFD 100%);
  background-attachment: fixed;
}

.logo-section {
  padding-top: 240rpx;
  margin-bottom: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .logo-image {
    width: 398rpx;
    height: 128rpx;
  }
}

.switch-section {
  text-align: center;
  margin-bottom: 80rpx;

  .switch-text {
    color: #999;
    font-size: 28rpx;
  }

  .switch-link {
    color: #0ed1ad;
    font-size: 28rpx;
    text-decoration: none;
  }
}

.form-section {
  margin-bottom: 100rpx;

  .input-item {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 12rpx;
    margin-bottom: 32rpx;
    position: relative;
    height: 96rpx;
    display: flex;
    width: 658rpx;
    align-items: center;

    &.dynamic-code {
      justify-content: space-between;
    }

    .input-field {
      flex: 1;
      width: 658rpx;
      height: 100%;
      padding: 0 32rpx;
      font-size: 32rpx;
      color: #333;
      border: none;
      border-radius: 24rpx;
      background: transparent;
      box-sizing: border-box;

      &::placeholder {
        color: #999;
      }
    }

    .clear-btn {
      position: absolute;
      right: 32rpx;
      width: 32rpx;
      height: 32rpx;
      background: #ccc;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 24rpx;
    }

    .send-code-btn {
      color: #0ed1ad;
      font-size: 28rpx;
      padding: 0 32rpx;
      white-space: nowrap;
    }
  }
}

.submit-btn {
  width: 668rpx;
  height: 92rpx;
  background: #d3f3ee;
  border-radius: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #0ed1ad;
  font-size: 36rpx;
  font-weight: 500;
  margin-bottom: 80rpx;
  letter-spacing: 8rpx;
  box-sizing: border-box;
}

.privacy-section {
  position: absolute;
  bottom: 80rpx;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 88rpx);
  display: flex;
  justify-content: center;

  .privacy-item {
    display: flex;
    align-items: center;

    .checkbox {
      width: 32rpx;
      height: 32rpx;
      border: 2rpx solid #ccc;
      border-radius: 50%;
      margin-right: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      &.checked {
        background: #4dd0e1;
        border-color: #4dd0e1;

        &::after {
          content: '✓';
          color: #fff;
          font-size: 20rpx;
          font-weight: bold;
        }
      }
    }

    .privacy-text {
      color: #666;
      font-size: 24rpx;
      line-height: 1.2;
    }

    .privacy-link {
      color: #4dd0e1;
      font-size: 24rpx;
      line-height: 1.2;
      text-decoration: none;
    }
  }
}
</style>

